const jsonServer = require('json-server')
const server = jsonServer.create()
const path = require('path')
const router = jsonServer.router(path.join(__dirname, 'vue.json'))
const middlewares = jsonServer.defaults()
const admins = [
    { id: 1, username: 'admin', password: 'admin_123456', name: '吴亦凡', token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsIm5hbWUiOiJhZG1pbiJ9.msGbgu59-Lc0LY4KzjqFzxZ59-i61iDgopl4m1XHyOk' },
    { id: 2, username: 'taru', password: 'taru_123456', name: '塔里木', token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0YXJ1IiwibmFtZSI6InRhcnUifQ._45DWObDnNUJt9Ixn9t7juMdUH31gLILzU_tBHOefyQ' }
];

server.use(middlewares)
    /*server.use((req, res, next) => {
        if (isAuthorized(req)) { // add your authorization logic here
            next() // continue to JSON Server router
        } else {
            res.sendStatus(401)
        }
    })
    */
    /*router.render = (req, res) => {
        res.jsonp({
            code: 200,
            data: res.locals.data,
            msg: "查询数据成功"
        })
    }
    */

server.use(jsonServer.bodyParser)
    //登陆接口
server.post('/api/login', function(req, res) {
        var username = req.body.username;
        var password = req.body.password;
        var obj;
        for (let admin of admins) {
            if (admin.username === username && admin.password === password) {
                obj = admin;
            }
        }
        if (obj) {
            res.jsonp({
                code: 200,
                data: obj,
                msg: "登陆查询成功"
            })
        } else {
            res.jsonp({
                code: 404,
                data: obj,
                msg: "用户名或者密码错误"
            })

        }

    })
    //查询所有的管理员账户
server.get('/admins', (req, res) => {
    res.jsonp(admins)
})


server.use(router)
server.listen(3000, () => {
    console.log('  \{^_^}/ hi!')
    console.log(' loadding db.json   done  at  3000  port ')

})